//
//  FlightResultListController.m
//  ELife
//
//  Created by xiaozhi on 11-5-24.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "FlightResultListController.h"
#import "FlightResultDetailController.h"
#import "FlightModel.h"
#import "GDataXMLNode.h"
#import "GTMBase64.h"
#import "ELifeAppDelegate.h"
#import "FlightSearchController.h"

@implementation FlightResultListController
@synthesize _tableView, _titleLabel;
FlightCity *_toCity;
FlightCity *_fromCity;

#pragma mark - network
- (void)request:(NSString *)fromCityCode withToCityCode:(NSString *)toCityCode
       withDate:(NSString *)date
{
    ELifeAppDelegate *app = [ELifeAppDelegate App];
    [app showProgressDialog:@"请稍候"];
    NSString* host =  [[NSBundle mainBundle] localizedStringForKey:(@"BussinessHost") value:@"" table:nil];
    NSURL* url = [[NSURL alloc] initWithString:[host stringByAppendingString:@"airline.php"]];
    
    NSMutableDictionary *param = [[NSMutableDictionary alloc]initWithCapacity:1];
    [param setObject:@"get_airline_list_for_mobile" forKey:@"action"];
    [param setObject:fromCityCode forKey:@"begin_city"];
    [param setObject:toCityCode forKey:@"end_city"];        
    [param setObject:date forKey:@"date"];
    [param setObject:@"300" forKey:@"limit"]; // 不需要分页现实 所以limit传大一些
    [param setObject:[[NSBundle mainBundle] localizedStringForKey:(@"ClientVersion") value:@"" table:nil] forKey:@"version"];
    
    NSDictionary* dic = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:url, @"requestFinished:", nil] forKeys:[NSArray arrayWithObjects:@"url", @"requestMethod", nil]];
    
    [[app httpRequestPoint]openUrl:dic postParam:param target:self];
    
    [param release];
}

- (void)setTitleWithFrom:(NSString *)from 
                      withArrive:(NSString *)arrive
                        withDate:(NSString *)date
                       withCount:(NSString *)count
{
    NSMutableString *mutableStr = [NSMutableString stringWithCapacity:30];
    
    [mutableStr appendFormat:@"%@-%@(%@)共搜索到(%@)个结果", from, arrive, date, count];
    [_titleLabel setText:mutableStr];
}

- (void)requestFinished:(NSData *)response
{
    [[ELifeAppDelegate App] hideProgressDialog];
    
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:[GTMBase64 decodeData:response] options:0 error:nil];
    GDataXMLElement* rootElement = [doc rootElement];    
    
    GDataXMLElement* bodyElement = [[rootElement elementsForName:@"body"]objectAtIndex:0];
    
    if (bodyElement == nil) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"没有您要搜索的机票结果" delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:nil, nil];
        [alert show];
        [alert release];
        [doc release];
        return;
    }
    
    GDataXMLElement* airLinesElement = [[bodyElement elementsForName:@"airlines"]objectAtIndex:0];
    
    // 设置titile
    NSString *airLineCount = [[[airLinesElement elementsForName:@"count"]objectAtIndex:0] stringValue];
    NSString *date = [[[airLinesElement elementsForName:@"Date"]objectAtIndex:0] stringValue];
    
    NSString *from = _fromCity._cityName;
    NSString *arrive = _toCity._cityName;
    
    
    [_curDate release];
    _curDate = [date retain];
    
    [self setTitleWithFrom:from
                withArrive:arrive
                withDate:date withCount:airLineCount];
    
    //  清空以前的机票信息
    [_flightList removeAllObjects];
    
    NSArray *airLineArr = [airLinesElement elementsForName:@"airline"];
    for (NSInteger index = 0; index < [airLineArr count]; index++) {
        GDataXMLElement *item = [airLineArr objectAtIndex:index];

        NSLog(@"----------flightModelitem:%@", item);

        FlightDetailModel *model = [[FlightDetailModel alloc] init];
        model.airCompany = [[[item elementsForName:@"AirCompany"]objectAtIndex:0]stringValue];
        model.flightNO = [[[item elementsForName:@"FlightNO"]objectAtIndex:0]stringValue];
        model.planeStyle = [[[item elementsForName:@"PlaneStyle"]objectAtIndex:0]stringValue];
        model.mile = [[[item elementsForName:@"Mile"]objectAtIndex:0]stringValue];
        model.basePrice = [[[item elementsForName:@"BasePrice"]objectAtIndex:0]stringValue];
        model.discount = [[[item elementsForName:@"Discount"]objectAtIndex:0]stringValue];
        model.airportTax = [[[item elementsForName:@"AirportTax"]objectAtIndex:0]stringValue];
        model.fuelTax = [[[item elementsForName:@"FuelTax"]objectAtIndex:0]stringValue];
        model.isStop = [[[item elementsForName:@"IsStop"]objectAtIndex:0]stringValue];
        model.depDateTime = [[[item elementsForName:@"DepDateTime"]objectAtIndex:0]stringValue];
        model.arriDateTime = [[[item elementsForName:@"ArriDateTime"]objectAtIndex:0]stringValue];
    
        [_flightList addObject:model];
        [model release];
    }

    _tableView.hidden = NO;
    [_tableView reloadData];
    
    [doc release];
}

- (void) iRequestFailed
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提醒" message:@"查询超时,请稍后重试" delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:nil, nil];
    [alert show];
    [alert release];
    [[ELifeAppDelegate App] hideProgressDialog];
}


- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)setSearchParam:(FlightCity *)fromCity withToCity:(FlightCity *)toCity
              withDate:(NSString *)date
{
    _fromCity = [fromCity retain] ;
    _toCity = [toCity retain];
    
    [date retain];
    _curDate = date;
    
    [self request:_fromCity._cityCode withToCityCode:toCity._cityCode withDate:date];
}

#pragma markend

// 根据索引得到对应的机票model
- (FlightDetailModel *)getFlightModelByIndex:(NSInteger)index
{
    return [_flightList objectAtIndex:index];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        _flightList = [[NSMutableArray alloc]initWithCapacity:30];
    }
    return self;
}

- (void)dealloc
{
    [_titleLabel release];
    [_tableView release];
    [_flightList release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.view.backgroundColor = [[UIColor alloc]
                                 initWithPatternImage:[UIImage imageNamed:@"bg.png"]];
    UIView *titleContainer = [self.view viewWithTag:TAG_TITLE_CONTAINER];
    titleContainer.layer.cornerRadius = 8;
    titleContainer.layer.masksToBounds = YES;
    
    [_tableView setRowHeight:96];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [_flightList count];
}

- (NSString *)getTimeString:(NSString *)date
{
    NSString *time = [date substringFromIndex:([date length] - 5)];
    return time;
}


// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)
- (void)fillCell:(UITableViewCell *)cell atIndex:(NSInteger)index
{
    UILabel *label1 = (UILabel *)[cell viewWithTag:TAG_CELL_LABEL1];
    UILabel *label2 = (UILabel *)[cell viewWithTag:TAG_CELL_LABEL2];
    UILabel *label3 = (UILabel *)[cell viewWithTag:TAG_CELL_LABEL3];
    UILabel *label4 = (UILabel *)[cell viewWithTag:TAG_CELL_LABEL4];
    UILabel *labelNo = (UILabel *)[cell viewWithTag:TAG_CELL_NO];
    [labelNo setText:[NSString stringWithFormat:@"%d", index + 1]];
    /*
     AirCompany = 航空公司
     FlightNO = 航班号
     Org = 始发城市
     Dst = 终点城市
     Date = 起飞日期
     PlaneStyle = 机型
     Mile = 飞行公里数
     BasePrice = 基价
     Discount 折扣 100 为100%
     AirportTax = 机场建设费
     FuelTax = 燃油税
     IsStop = 经停
     DepDateTime = 起飞时间
     ArriDateTime = 降落时间
     */
    
    FlightDetailModel *flightModel = [self getFlightModelByIndex:index];

    [label1 setText:[NSString stringWithFormat:@"%@ / %@", flightModel.flightNO, flightModel.planeStyle]];
    
    NSString *time = [self getTimeString:(flightModel.depDateTime)];
    [label2 setText:[NSString stringWithFormat:@"%@ %@", time, _fromCity._airportName]];
    
    time = [self getTimeString:flightModel.arriDateTime];
    [label3 setText:[NSString stringWithFormat:@"%@ %@", time, _toCity._airportName]];
    
    
    NSString *price = flightModel.basePrice;
    double discount = [flightModel.discount doubleValue];
    
    NSString *discountStr = @"无折扣";
    if (discount != 100) { // 计算折扣
        double discountF = discount / 10;
        discountStr = [NSString stringWithFormat:@"%f", discountF];
        discountStr = [discountStr substringToIndex:3];
        discountStr = [NSString stringWithFormat:@"%@折", discountStr];
    }
    [label4 setText:[NSString stringWithFormat:@"%@元 %@", price, discountStr]];

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    static NSString *CELL_NIB_NAME = @"FlightResultListCell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        NSArray *array = [[NSBundle mainBundle] loadNibNamed:CELL_NIB_NAME owner:self options:nil];
        cell = (UITableViewCell *)[array objectAtIndex:0];
    }

    [self fillCell:cell atIndex:indexPath.section];    
    return cell;
}

#pragma mark - selection
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger index = indexPath.section;
    FlightDetailModel *flightModel = [self getFlightModelByIndex:index];
    
    FlightResultDetailController *detailController = [[FlightResultDetailController alloc]initWithNibName:@"FlightResultDetailController" bundle:nil];
    [detailController setFlightList:flightModel  
                    withFromAirport:_fromCity._airportName
                  withArriveAirport:_toCity._airportName
                           withDate:_curDate];
    
    [FlightSearchController getCheckedModel].startCity = _fromCity._cityCode;
    [FlightSearchController getCheckedModel].endCity = _toCity._cityCode;

    
    [self.navigationController pushViewController:detailController animated:YES];
    [detailController release];
}


#pragma mark - ibaction

- (void)orderByDate
{
    NSInteger count = [_flightList count];
    FlightDetailModel *temp;
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm"];
    
    for (NSInteger i = 0; i < count; i++) {
        for (NSInteger j = 0; j < count - i - 1; j++) {
            FlightDetailModel *preModel = [_flightList objectAtIndex:j];
            FlightDetailModel *afterModel = [_flightList objectAtIndex:j + 1];
            NSDate *preDate = [dateFormatter dateFromString:preModel.depDateTime];
            NSDate *nextDate = [dateFormatter dateFromString:afterModel.depDateTime];
            if ([nextDate compare:preDate] == (NSComparisonResult)NSOrderedDescending) {
                temp = preModel;
                preModel = afterModel;
                afterModel = temp;
            }
        }
    }
    
    [dateFormatter release];
}

- (void)orderByPrice
{
    NSInteger count = [_flightList count];
    FlightDetailModel *temp;
    for (NSInteger i = 0; i < count; i++) {
        for (NSInteger j = 0; j < count - i - 1; j++) {
            FlightDetailModel *preModel = [_flightList objectAtIndex:j];
            FlightDetailModel *afterModel = [_flightList objectAtIndex:j + 1];
            NSInteger prePrice = [preModel.basePrice intValue];
            NSInteger nextPrice = [afterModel.basePrice intValue];;
            if (prePrice < nextPrice) {
                temp = preModel;
                preModel = afterModel;
                afterModel = temp;
            }
        }
    }
}

- (void)orderAction:(id)sender
{
    UISegmentedControl *segmentControl = (UISegmentedControl *)sender;
    unsigned int selectedIndex = [segmentControl selectedSegmentIndex];
    switch (selectedIndex) {
        case 0: // date order
            [self orderByDate];
            break;
        case 1: // price order
            [self orderByPrice];
            break;
            
        default:
            break;
    }
    
    [_tableView reloadData];
}

- (void)showDatePicker
{
    NSString *title = UIDeviceOrientationIsLandscape([UIDevice currentDevice].orientation) ? @"\n\n\n\n\n\n\n\n\n" : @"\n\n\n\n\n\n\n\n\n\n\n\n" ;
    UIActionSheet *actionSheet = [[UIActionSheet alloc] 
                                  initWithTitle:title 
                                  delegate:self 
                                  cancelButtonTitle:@"取消" 
                                  destructiveButtonTitle:@"设置"
                                  otherButtonTitles:nil];
    
    UIDatePicker *datePicker = [[UIDatePicker alloc] init];
    datePicker.datePickerMode = UIDatePickerModeDate;
    datePicker.tag = TAG_DATE_PICKER;
    [actionSheet addSubview:datePicker];
    [datePicker release];
    
    [actionSheet showInView:self.view];
    [actionSheet release];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"YYYY-MM-dd";
        
        UIDatePicker *datePicker = (UIDatePicker *)[actionSheet viewWithTag:TAG_DATE_PICKER];
        NSString *timestamp = [formatter stringFromDate:datePicker.date];
        
        [self request:_fromCity._cityCode withToCityCode:_toCity._cityCode withDate:timestamp];
        [formatter release];
    }
}

- (void)ealierDay
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"YYYY-MM-dd"];
    
    NSDate *date = [dateFormatter dateFromString:_curDate];
    
    NSDate *ealierDate = [date addTimeInterval:-(60 * 60 * 24)];
    
    NSString *ealierDateStr = [dateFormatter stringFromDate:ealierDate];    
    
    [self request:_fromCity._cityCode withToCityCode:_toCity._cityCode withDate:ealierDateStr];
    
    [dateFormatter release];
}

- (void)afterDay
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"YYYY-MM-dd"];
    
    NSDate *date = [dateFormatter dateFromString:_curDate];
    NSDate *afterDate = [date addTimeInterval:60 * 60 * 24];
    
    
    NSString *afterDateStr = [dateFormatter stringFromDate:afterDate];  

    [self request:_fromCity._cityCode withToCityCode:_toCity._cityCode withDate:afterDateStr];
    
    [dateFormatter release];
}

- (void)dateAction:(id)sender
{
    UISegmentedControl *segmentControl = (UISegmentedControl *)sender;
    unsigned int selectedIndex = [segmentControl selectedSegmentIndex];
    switch (selectedIndex) {
        case 0: //前一天
            [self ealierDay];
            break;
        case 1: //弹出日期选择
            [self showDatePicker];
            break;
        case 2: //后1天
            [self afterDay];
            break;
            
        default:
            break;
    }
}
@end
